package com.fangcang.zookeeper;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperUtil {
	
	public ZooKeeper getZkClient() {
		ZooKeeper zookeeper = null;
		try {
			zookeeper= new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					System.out.println(event.getType().name());
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		return zookeeper;
	}
	
	public void getChildren(	ZooKeeper zookeeper, String path, boolean isRoot) {
	
		try {
			List<String> list = zookeeper.getChildren(path, false);
			if(null != list && !list.isEmpty()) {
				for(String subPath : list) {
					System.out.println(subPath);
					getChildren(zookeeper, (isRoot ? path : (path + "/"))+subPath, false);
				}
			}
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void getZkTree() {
		ZooKeeper zookeeper = getZkClient();
		getChildren(zookeeper, "/",  true);
	}
	
	public static void main(String[] args) {
		ZookeeperUtil zk = new ZookeeperUtil();
		zk.getZkTree();
	}
}
